import os
import uuid
from flask import request, send_file
from result.result import Result
from result.result_code import ResultCode


class FileService(object):
    @staticmethod
    def upload_file():
        # 生成保存文件的目录，如果不存在则创建
        save_dir = '.\\static\\upload'
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        if 'file' not in request.files:
            return Result.error(ResultCode.DATA_ERROR.value, "未上传文件")
        file = request.files['file']
        if file.filename == '':
            return Result.error(ResultCode.DATA_ERROR.value, "未找到文件")
        if file:
            # 保存文件
            allowed_extensions = ["png", "jpg", "jpeg", "webp", 'bmp', 'dng', 'mpo', 'tif', 'tiff', 'pfm', 'HEIC', "mp4", "avi", "gif", "m4v", "asf", "mkv", "mov", "mpeg", "mpg", "ts", "wmv", "webm"]
            if file.filename.split('.')[-1] not in allowed_extensions:
                return Result.error(ResultCode.DATA_CHECK_ERROR.value, "文件格式不合法")
            try:
                file_name = str(uuid.uuid4()) + '.' + file.filename.split('.')[-1]
                # print(filename)
                file_path = os.path.join(save_dir, file_name)
                file.save(file_path)
            except Exception:
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, "文件上传失败，服务器错误")
            return Result.success_data(file_name)

    @staticmethod
    def delete_file(file_path):
        if not os.path.exists(file_path):
            return Result.error(ResultCode.NOT_FOUND.value, "文件资源不存在")
        else:
            try:
                os.remove(file_path)
            except Exception:
                return Result.error(ResultCode.INTERNAL_SERVER_ERROR.value, '文件删除失败')
            return Result.success()

    @staticmethod
    def download(file_type, file_name):
        if file_type == 'upload':
            file_path = ".\\static\\upload\\" + file_name
        elif file_type == 'result':
            file_path = ".\\static\\detect\\" + file_name
            contents = os.listdir(file_path)
            if len(contents) != 1 or not os.path.isfile(os.path.join(file_path, contents[0])):
                return Result.error(ResultCode.NOT_FOUND.value, "资源出错")
            file_path = os.path.join(file_path, contents[0])
            print(file_path)
        else:
            return Result.error(ResultCode.DATA_ERROR.value, "不存在的类型")
        # print(file_path)

        if not os.path.exists(file_path):
            return Result.error(ResultCode.NOT_FOUND.value, "文件不存在")
        return send_file(file_path, as_attachment=False)

